<template>
  <view class="container">
    <view class="bg-fff p-2 rounded20 mb-2 gameBox">
      <!--    <view class="d-flex d-flex-around p-5  bg">-->
      <!--      <view class="d-flex-column text-center">-->
      <!--        <text class="font50">171</text>-->
      <!--        <text>接单总量</text>-->
      <!--      </view>-->
      <!--      <view class="d-flex-column text-center">-->
      <!--        <text class="font50">171</text>-->
      <!--        <text>服务人数</text>-->
      <!--      </view>-->
      <!--    </view>-->
      <view class="py-2 font32">基础信息</view>
      <view class="p-item  rounded20">
        <view class="py-2 mx-2 d-flex d-flex-middle d-flex-between bBottom" @click="openTextIntroduction">
          <view class="font26 " style="width: 150rpx;">
            <text class="color666">文字介绍</text>
          </view>
          <view class="d-flex-item py-1-5 px-1 text-right">
            <text :class="{'colorhold': !formData.characters_introduce}">{{
                formData.characters_introduce || '请详细介绍你的游戏特色'
              }}
            </text>
          </view>
          <text class="iconfont icon-youjiantou color999 "></text>
        </view>
        <view class="py-2 mx-2 d-flex d-flex-middle d-flex-between" @click="openVoiceIntroduction">
          <view class="font26 " style="width: 150rpx;">
            <text class="color666">语音介绍</text>
          </view>
          <view class="d-flex-item py-1-5 px-1 text-right">
            <text :class="{'colorhold': !formData.voice_introduce}">{{
                formData.voice_introduce ? '已上传' : '未上传'
              }}
            </text>
          </view>
          <text class="iconfont icon-youjiantou color999 "></text>
        </view>
      </view>

      <!--      <view class="py-2 font32">游戏信息</view>-->
      <!--      <view class="p-item  rounded20">-->
      <!--        <view class="py-2 mx-2 d-flex d-flex-middle d-flex-between bBottom" @click="openSkillImage">-->
      <!--          <view class="font26 " style="width: 150rpx;">-->
      <!--            <text class="color666">技能图</text>-->
      <!--          </view>-->
      <!--          <view class="d-flex-item py-1-5 px-1 text-right">-->
      <!--            <text :class="{'colorhold': !formData.skillImage}">{{ formData.skillImage ? '已上传' : '未上传' }}</text>-->
      <!--          </view>-->
      <!--          <text class="iconfont icon-youjiantou color999 "></text>-->
      <!--        </view>-->
      <!--        <view class="py-2 mx-2 d-flex d-flex-middle d-flex-between" @click="openRank">-->
      <!--          <view class="font26 " style="width: 150rpx;">-->
      <!--            <text class="color666">段位</text>-->
      <!--          </view>-->
      <!--          <view class="d-flex-item py-1-5 px-1 text-right">-->
      <!--            <text :class="{'colorhold': !formData.rank}">{{ formData.rank || '请选择段位' }}</text>-->
      <!--          </view>-->
      <!--          <text class="iconfont icon-youjiantou color999 "></text>-->
      <!--        </view>-->
      <!--      </view>-->

      <!--      <view class="py-2 font32">游戏范围</view>-->
      <!--      <view class="p-item  rounded20">-->
      <!--        <view class="py-2 mx-2 d-flex d-flex-middle d-flex-between " @click="openGameArea">-->
      <!--          <view class="font26 " style="width: 150rpx;">-->
      <!--            <text class="color666">游戏大区</text>-->
      <!--          </view>-->
      <!--          <view class="d-flex-item py-1-5 px-1 text-right">-->
      <!--            <text :class="{'colorhold': !formData.gameArea}">{{ formData.gameArea || '请选择游戏大区' }}</text>-->
      <!--          </view>-->
      <!--          <text class="iconfont icon-youjiantou color999 "></text>-->
      <!--        </view>-->
      <!--      </view>-->

      <view class="py-2 font32">基础定价</view>
      <view class="p-item  rounded20">
        <view class="py-2 mx-2 d-flex d-flex-middle d-flex-between " @click="openPriceSetting">
          <view class="font26 " style="width: 300rpx;">
            <text class="colorf00 font40">{{ formData.skill_price || 0 }}元/</text>
            <text>小时</text>
          </view>
          <view class="d-flex-item py-1-5 px-1 text-right">
            <text class="colorhold">{{ formData.skill_price ? '修改价格' : '设置价格' }}</text>
          </view>
          <text class="iconfont icon-youjiantou color999 "></text>
        </view>
      </view>
    </view>

    <view class="fixedBtn bg-fff pb-5 pt-3 px-2">
      <view  @click="handleSubmit" class="money-sure-btn-bg bgcolor598dfc colorfff d-flex d-flex-middle d-flex-center font30">修改技能</view>
    </view>

    <!-- 文字介绍弹窗 -->
    <uni-popup ref="textIntroPopup" :safe-area="false" type="bottom">
      <view class="popup-content bg-fff">
        <view class="popup-header d-flex d-flex-between p-3">
          <text></text>
          <text class="font32">文字介绍</text>
          <text @click="closeTextIntroPopup">完成</text>
        </view>
        <textarea
            class="note-textarea p-2 my-2 mx-3 rounded20"
            placeholder="请详细介绍你的游戏特色"
            placeholder-class="color999"
            v-model="formData.characters_introduce"
            :maxlength="200"
            style="height: 200rpx;"
        ></textarea>
      </view>
    </uni-popup>

    <!-- 价格设置弹窗 -->
    <uni-popup ref="pricePopup" :safe-area="false" type="bottom">
      <view class="popup-content bg-fff">
        <view class="popup-header d-flex d-flex-between p-3">
          <text></text>
          <text class="font32">设置价格</text>
          <text @click="closePricePopup">完成</text>
        </view>
        <view class="p-3 d-flex d-flex-middle pb-5">
          <input
              type="digit"
              class="price-input p-2 rounded20 colorf00"
              placeholder="请输入每小时价格"
              v-model="formData.skill_price"
          />
          <text class="font26 colorf00 ml-2">元/小时</text>
        </view>
      </view>
    </uni-popup>

    <!-- 语音介绍弹窗 -->
    <uni-popup ref="voiceIntroPopup" :safe-area="false" type="bottom">
      <view class="popup-content bg-fff">
        <view class="popup-header d-flex d-flex-between p-3">
          <text></text>
          <text class="font32">语音介绍</text>
          <text @click="closeVoiceIntroPopup">完成</text>
        </view>
        <view class="p-3">
          <view class="voice-upload-area d-flex d-flex-column d-flex-center p-4 rounded20"
                :class="{'voice-uploaded': formData.voice_introduce}"
                @click="handleVoiceAreaClick">
            <view v-if="!formData.voice_introduce" class="d-flex d-flex-column d-flex-center">
              <text class="iconfont icon-luyin font50 color598dfc mb-2"></text>
              <text class="font26 color666">点击录制语音介绍</text>
              <text class="font24 color999 mt-1">建议时长30秒-2分钟</text>
            </view>
            <view v-else class="d-flex d-flex-column d-flex-center">
              <text class="iconfont icon-yuyin font50 color598dfc mb-2"></text>
              <text class="font26 color666">已上传语音介绍</text>
              <text class="font24 color598dfc mt-1" @click.stop="playVoice">点击播放</text>
            </view>
          </view>

          <!-- 添加删除按钮 -->
          <view v-if="formData.voice_introduce" class="d-flex d-flex-center mt-3">
            <view class="delete-btn d-flex d-flex-middle px-3 py-1 rounded30" @click="deleteVoice">
              <text class="iconfont icon-shanchu colorf00 mr-1"></text>
              <text class="font26 colorf00">删除语音</text>
            </view>
          </view>

          <!-- 录音状态显示 -->
          <view v-if="isRecording" class="recording-status d-flex d-flex-column d-flex-center mt-3">
            <text class="iconfont icon-luxiangzhong font50 colorf00 mb-2"></text>
            <text class="font26 colorf00">录制中...{{ recordingTime }}s</text>
            <view class="d-flex mt-3">
              <view class="cancel-btn mr-3" @click="cancelRecording">取消</view>
              <view class="finish-btn" @click="finishRecording">完成</view>
            </view>
          </view>
        </view></view>
    </uni-popup>
  </view>
</template>

<script>
import {fileApi} from '@/http/fileApi.js';
import {mapState} from "vuex";

export default {
  data() {
    return {
      formData: {
        id: '',
        characters_introduce: '',
        voice_introduce: '',
        skill_price: ''
      },
      isRecording: false, // 是否正在录音
      recordingTime: 0,   // 录音时长
      recorderManager: null, // 录音管理器
      innerAudioContext: null, // 音频播放上下文
      voiceFilePath: '', // 语音文件路径
      recordingTimer: null // 录音计时器
    }
  },
  computed: {
    ...mapState({
      id: state => state.id,
      loginState: state => state.loginState
    })
  },
  mounted() {
    // 初始化录音管理器
    this.initRecorder();
    // 初始化音频播放器
    this.initAudioPlayer();
    //   技能详情
    this.initInfo()
  },
  beforeDestroy() {
    // 销毁音频播放器
    if (this.innerAudioContext) {
      this.innerAudioContext.destroy();
    }
    // 清除计时器
    if (this.recordingTimer) {
      clearInterval(this.recordingTimer);
    }
  },
  onLoad(option) {
    if (option.id) {
      this.formData.id = option.id
    }
    // 初始化录音管理器
    this.$nextTick(() => {
      this.initRecorder();
    });
  },
  methods: {
    async initInfo() {
      let res = await fileApi.getHandSkillInfo({id: this.formData.id})
      this.formData.characters_introduce = res.characters_introduce;
      this.formData.voice_introduce = res.voice_introduce;
      this.formData.skill_price = res.skill_price;
    },
    // 初始化录音管理器
    initRecorder() {
      this.recorderManager = uni.getRecorderManager();

      // 监听录音开始事件
      this.recorderManager.onStart(() => {
        console.log('录音开始');
        this.isRecording = true;
        this.startRecordingTimer();
      });

      // 监听录音结束事件
      this.recorderManager.onStop((res) => {
        console.log('录音结束', res);
        this.isRecording = false;
        this.stopRecordingTimer();
        this.voiceFilePath = res.tempFilePath;

        // 上传录音文件
        this.uploadVoiceFile(res.tempFilePath);
      });

      // 监听录音错误事件
      this.recorderManager.onError((res) => {
        console.error('录音失败', res);
        this.isRecording = false;
        this.stopRecordingTimer();
        uni.showToast({
          title: '录音失败',
          icon: 'none'
        });
      });
    },

    // 初始化音频播放器
    initAudioPlayer() {
      this.innerAudioContext = uni.createInnerAudioContext();

      this.innerAudioContext.onPlay(() => {
        console.log('开始播放');
      });

      this.innerAudioContext.onStop(() => {
        console.log('停止播放');
      });

      this.innerAudioContext.onEnded(() => {
        console.log('播放结束');
      });

      this.innerAudioContext.onError((res) => {
        console.error('播放失败', res);
        uni.showToast({
          title: '播放失败',
          icon: 'none'
        });
      });
    },

    // 打开文字介绍弹窗
    openTextIntroduction() {
      this.$refs.textIntroPopup.open();
    },

    // 关闭文字介绍弹窗
    closeTextIntroPopup() {
      this.$refs.textIntroPopup.close();
    },

    // 打开语音介绍弹窗
    openVoiceIntroduction() {
      this.$refs.voiceIntroPopup.open();
    },

    // 关闭语音介绍弹窗
    closeVoiceIntroPopup() {
      // 如果正在录音，先停止录音
      if (this.isRecording && this.recorderManager) {
        this.recorderManager.stop();
      }

      // 重置录音相关状态
      this.isRecording = false;
      this.recordingTime = 0;

      // 清除录音计时器
      if (this.recordingTimer) {
        clearInterval(this.recordingTimer);
        this.recordingTimer = null;
      }

      this.$refs.voiceIntroPopup.close();
    },
    // 打开技能图
    openSkillImage() {
      uni.showToast({
        title: '技能图查看功能待开发',
        icon: 'none'
      });
    },

    // 打开段位选择
    openRank() {
      uni.showToast({
        title: '段位选择功能待开发',
        icon: 'none'
      });
    },

    // 打开游戏大区选择
    openGameArea() {
      uni.showToast({
        title: '游戏大区选择功能待开发',
        icon: 'none'
      });
    },

    // 打开价格设置弹窗
    openPriceSetting() {
      this.$refs.pricePopup.open();
    },

    // 关闭价格设置弹窗
    closePricePopup() {
      this.$refs.pricePopup.close();
    },


    // 开始录音
    startRecording() {
      // 根据不同平台设置录音参数
      const options = {
        duration: 120000, // 最长录音时长 2 分钟
        sampleRate: 16000, // 采样率
        numberOfChannels: 1, // 录音通道数
        encodeBitRate: 96000, // 编码码率
        format: 'mp3', // 音频格式
      };

      // 针对不同平台的特殊处理
      // #ifdef H5
      // H5平台可能不支持mp3格式，使用aac作为备选
      options.format = 'aac';
      // #endif

      // #ifdef MP-WEIXIN
      // 微信小程序可能需要不同的参数
      options.frameSize = 50;
      // #endif

      this.recorderManager.start(options);
    },

    // 停止录音
    stopRecording() {
      this.recorderManager.stop();
    },

    // 开始录音计时
    startRecordingTimer() {
      this.recordingTime = 0;
      this.recordingTimer = setInterval(() => {
        this.recordingTime++;
      }, 1000);
    },

    // 停止录音计时
    stopRecordingTimer() {
      if (this.recordingTimer) {
        clearInterval(this.recordingTimer);
        this.recordingTimer = null;
      }
    },

    // 上传语音
    handleVoiceAreaClick() {
      // 如果正在录音，不处理点击事件
      if (this.isRecording) {
        return;
      }
      // 如果已有语音，播放语音
      if (this.formData.voice_introduce) {
        this.playVoice();
      } else {
        // 如果没有语音，开始录音
        this.startVoiceRecording();
      }
    },

    // 开始语音录制
    startVoiceRecording() {
      // 显示操作选项
      uni.showActionSheet({
        itemList: ['录制语音'],
        success: (res) => {
          if (res.tapIndex === 0) {
            // 录制语音
            this.startRecording();
          }
        },
        fail: (err) => {
          console.log('取消录音操作');
        }
      });
    },


    // 上传语音文件
    async uploadVoiceFile(filePath) {
      uni.showLoading({
        title: '上传中...'
      });

      try {
        // 调用文件上传API
        const res = await fileApi.upload(filePath);

        uni.hideLoading();

        if (res && res.data) {
          this.formData.voice_introduce = res.data;
          this.voiceFilePath = filePath;
          uni.showToast({
            title: '上传成功',
            icon: 'success'
          });
          this.$refs.voiceIntroPopup.close()
        } else {
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          });
        }
      } catch (err) {
        uni.hideLoading();
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        });
        console.error('上传语音失败:', err);
      }
    },

    // 播放语音
    playVoice() {
      if (!this.voiceFilePath && this.formData.voice_introduce) {
        // 如果有语音介绍但没有本地路径，使用服务器路径
        this.innerAudioContext.src = this.formData.voice_introduce;
      } else if (this.voiceFilePath) {
        // 使用本地路径
        this.innerAudioContext.src = this.voiceFilePath;
      } else {
        uni.showToast({
          title: '暂无语音介绍',
          icon: 'none'
        });
        return;
      }

      this.innerAudioContext.play();
    },

    // 取消录音
    cancelRecording() {
      this.recorderManager.stop();
      this.isRecording = false;
      this.stopRecordingTimer();
    },

    // 完成录音
    finishRecording() {
      this.stopRecording();
    },
    // 删除语音
    deleteVoice() {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除已上传的语音介绍吗？',
        success: (res) => {
          if (res.confirm) {
            this.formData.voice_introduce = '';
            this.voiceFilePath = '';

            // 如果正在播放，停止播放
            if (this.innerAudioContext) {
              this.innerAudioContext.stop();
            }

            // 重置录音状态
            this.isRecording = false;
            this.recordingTime = 0;

            // 清除录音计时器
            if (this.recordingTimer) {
              clearInterval(this.recordingTimer);
              this.recordingTimer = null;
            }

            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
          }
        }
      });
    },
    async handleSubmit() {
      if (!this.loginState) {
        uni.showToast({
          title: '未登录，请先登录！',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/login'
          });
        }, 1500);
        return;
      }

      // 表单验证
      if (!this.formData.characters_introduce) {
        uni.showToast({
          title: '请填写文字介绍',
          icon: 'none'
        });
        return;
      }

      if (!this.formData.skill_price) {
        uni.showToast({
          title: '请设置价格',
          icon: 'none'
        });
        return;
      }


      if (!this.formData.voice_introduce) {
        uni.showToast({
          title: '请上传语音介绍',
          icon: 'none'
        });
        return;
      }

      uni.showLoading({
        title: '提交中...',
        mask: true
      });

      try {
        // 调用API提交数据
        const res = await fileApi.handInfo(this.formData);

        uni.hideLoading();
        uni.showToast({
          title: '提交成功',
          icon: 'success'
        });

        // 返回上一页
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } catch (err) {
        uni.hideLoading();
        uni.showToast({
          title: '提交失败',
          icon: 'none'
        });
        console.error('提交失败:', err);
      }
    }
  }
}
</script>

<style scoped>
.container {
  position: relative;
  background-color: #f4f6fa;
  min-height: 100vh;
}

.bg {
  background-image: linear-gradient(to bottom, #d3dcfb, #e3ebfb);
  background-color: #f4f6fa;
  padding-bottom: 80rpx;
}

.form-row {
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid #eee;
}

.bBottom {
  border-bottom: 1rpx solid #eee;
}

.label {
  width: 160rpx;
}

input {
  flex: 1;
  height: 80rpx;
  font-size: 28rpx;
}

.section-title {
  display: block;
}

.photo-grid {
  display: flex;
  justify-content: space-between;
}

.photo-item {
  width: 48%;
  height: 180rpx;
  overflow: hidden;
}

.placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #FC6127;
}

.colorFC6127 {
  border: 1rpx dashed #FC6127;
}

.placeholder .img {
  width: 30%;
}

.submit-btn {
  background: #598dfc;
  color: white;
}

.submit-btn[disabled] {
  opacity: 0.6;
}

.color598dfc {
  color: #598dfc;
}

.color598dfc5 {
  background: rgba(89, 141, 252, .2);
}

.note-textarea {
  background: #f9f9f9;
  width: 93%;
}

.price-input {
  border: 1rpx solid #eee;
  width: 60%;
}

.money-sure-btn-bg {
  border-radius: 50rpx;
  height: 84rpx;
  width: 690rpx;
}

.bgcolor598dfc {
  background-color: #598dfc;
}

.fixedBtn {
  position: fixed;
  bottom: 0;
  width: calc(100% - 40rpx);
}

.gameBox {
  border-top-right-radius: 30rpx;
  border-top-left-radius: 30rpx;
  position: relative;
  top: -20rpx;
  background: #f4f6fa;
}

.p-item {
  background-color: rgba(255, 255, 255, .8);
  padding-top: 25rpx;
  padding-bottom: 25rpx;
  margin-bottom: 4rpx;
}

.popup-content {
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  width: 100%;
  padding-bottom: 100rpx;
}

.colorhold {
  color: #999;
}

.colorf00 {
  color: #f00;
}

.color999 {
  color: #999;
}

.voice-upload-area {
  border: 1rpx dashed #598dfc;
  background-color: #f0f4ff;
  transition: all 0.3s;
}

.voice-upload-area:hover,
.voice-uploaded {
  background-color: #e1e9ff;
}

.recording-status {
  color: #f00;
}

.cancel-btn,
.finish-btn {
  padding: 10rpx 30rpx;
  border-radius: 30rpx;
  color: #fff;
}

.cancel-btn {
  background-color: #ccc;
}

.finish-btn {
  background-color: #598dfc;
}

.delete-btn {
  border: 1rpx solid #f00;
}

.delete-btn:hover {
  background-color: #fff5f5;
}

.colorf00 {
  color: #f00;
}

</style>
